'use strict';

//#region 信息展示工具

/**
 * 用于信息展示的父类
 */
class InfoShower {
    shower = null;
    static log(infoShowerList, msg) { infoShowerList.forEach(element => { element.log(msg); }); }
    static warn(infoShowerList, msg) { infoShowerList.forEach(element => { element.warn(msg); }); }
    static error(infoShowerList, msg) { infoShowerList.forEach(element => { element.error(msg); }); }
    constructor(shower) { this.shower = shower; }
    initInfoShowZoom(info) { }
    log(msg) { }
    warn(msg) { }
    error(msg) { }
}

class ConsoleLogger extends InfoShower {
    static #_instance = null;
    static get instance() {
        if (!ConsoleLogger.#_instance) { ConsoleLogger.#_instance = new ConsoleLogger(); }
        return ConsoleLogger.#_instance;
    }
    constructor() { super(console); }
    log(msg) {
        this.shower.log(`%c${msg}`, 'color:#0080FF;background:#f0f3ff;');
    }
    warn(msg) {
        this.shower.warn(msg);
    }
    error(msg) {
        this.shower.error(msg);
    }
}

class PageMessageShower extends InfoShower {
    static #instance = null;
    static #MAX_MESSAGE_COUNT = 15;
    static #ID_MESSAGEBOX = 'messagebox';
    static #TRANSITION_DURATION = '0.3s'; // 动画过渡时间
    static #ID_MESSAGEBOX_CONTROL_PANEL = 'controlPanel';
    static #ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE = 'btnToggleScriptPauseState';
    /** 显示消息的元素的ID */
    static #ID_MESSAGEBOX_CONTENT = 'messageContent';
    static #BTN_PAUSE_TEXT = '|| 暂停运行';
    static #BTN_RESUME_TEXT = '▶️ 继续运行';
    static #TEXT_TIP_SHRINK = '点击缩小';
    static #TEXT_TIP_ENLARGE = '点击还原';
    static #ID_SCRIPT_PAUSE_STATE = 'pauseState';
    static getInstance(scriptControlChannelName = 'scriptControlChannel') {
        if (!PageMessageShower.#instance) {
            PageMessageShower.#instance = new PageMessageShower(scriptControlChannelName);
        }
        return PageMessageShower.#instance;
    }
    #scriptPauseStateMessageChannel = null;
    #messagebox = null;
    constructor(scriptControlChannelName) {
        super(null);
        this.#scriptPauseStateMessageChannel = new BroadcastChannel(scriptControlChannelName);
    }
    /**
     * 获取消息框元素
     * @returns {HTMLElement|null} 消息框元素，如果未找到则返回null
     */
    #getMessagebox() {
        if (this.#messagebox) { return this.#messagebox; }
        return (this.#messagebox = document.getElementById(PageMessageShower.#ID_MESSAGEBOX));
    }
    //#region Messagebox创建及行为设定
    /**
         * 初始化信息展示区域
         * @param {string} insertParentSelector 要插入的父元素选择器
         * @returns
         */
    initInfoShowZoom(insertParentSelector) {
        if (this.#getMessagebox()) { return; }
        //#region 向页面注入Messagebox所需样式
        const messageboxCSS =
            `:root{--msgbox-bg:rgba(255,255,255,0.98);--msgbox-border:1px solid rgba(0,0,0,0.1);--btn-primary-bg:linear-gradient(135deg,#6B8DD6 0%,#8E37D7 100%);--btn-danger-bg:linear-gradient(135deg,#FF6B6B 0%,#FF8E53 100%);--btn-text:white;--shadow:0 8px 32px rgba(0,0,0,0.1);--corner-radius:12px}
            #${PageMessageShower.#ID_MESSAGEBOX}{position:fixed !important;left:20px !important;top:20px !important;z-index:99999;backdrop-filter:blur(10px);transform:translateZ(0);transition:all ${PageMessageShower.#TRANSITION_DURATION}
            cubic-bezier(0.4,0,0.2,1) !important;box-shadow:var(--shadow) !important;border-radius:var(--corner-radius) !important;border:var(--msgbox-border) !important;background:var(--msgbox-bg) !important}
            #${PageMessageShower.#ID_MESSAGEBOX_CONTENT} ::-webkit-scrollbar{width:6px;background-color:rgba(0,0,0,0.05)}
            #${PageMessageShower.#ID_MESSAGEBOX_CONTENT}::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,0.2);border-radius:4px}
            #${PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE}{font-weight:500 !important;letter-spacing:0.5px;transition:all 0.2s !important;border-radius:8px !important;text-shadow:0 1px 2px rgba(0,0,0,0.1)}
            #${PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE}:hover{opacity:0.9 !important;transform:scale(0.98)}
            .minimized{width:40px !important;height:40px !important;overflow:hidden !important;display:flex !important;align-items:center;justify-content:center;cursor:pointer !important}
            .minimized #${PageMessageShower.#ID_MESSAGEBOX_CONTROL_PANEL},.minimized #${PageMessageShower.#ID_MESSAGEBOX_CONTENT}{display:none !important}
            .minimized::after{content:"⤡";color:var(--btn-primary-bg);font-size:16px;position:absolute}`;
        const styleSheet = document.createElement('style');
        styleSheet.textContent = messageboxCSS;
        document.head.appendChild(styleSheet);
        //#endregion
        const messageboxHtml = `
        <div id="${PageMessageShower.#ID_MESSAGEBOX}" title = "${PageMessageShower.#TEXT_TIP_SHRINK}" style="width: 300px;height: 420px;display: flex;flex-direction: column;">
            <div id="${PageMessageShower.#ID_MESSAGEBOX_CONTROL_PANEL}" style="padding: 12px;border-bottom: 1px solid rgba(0,0,0,0.05);">
                <button id="${PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE}"
                        title="" style="width: 100%;padding: 10px;background: var(--btn-primary-bg);color: var(--btn-text);
                        border: none;font-size: 14px;">${PageMessageShower.#BTN_PAUSE_TEXT}</button>
            </div>
            <div id="${PageMessageShower.#ID_MESSAGEBOX_CONTENT}" style="flex: 1;padding: 12px;font-size: 13px;line-height: 1.5;overflow-y: auto;"></div>
        </div>`;
        document.querySelector(insertParentSelector).insertAdjacentHTML('beforeend', messageboxHtml);
        this.#initMessageboxControls();
        this.#listenScriptPauseStateChange();
    }
    /**
     * 切换Messagebox展开折叠状态
     * @returns
     */
    #toggleMessagebox() {
        const messagebox = PageMessageShower.getInstance().#getMessagebox();
        if (!messagebox) { return; }
        messagebox.classList.toggle('minimized');

        // 添加缩放动画
        if (messagebox.classList.contains('minimized')) {
            messagebox.title = PageMessageShower.#TEXT_TIP_ENLARGE;
            messagebox.style.transform = 'scale(0.9)';
            setTimeout(() => { messagebox.style.transform = 'scale(1)' }, 300);
        } else {
            messagebox.title = PageMessageShower.#TEXT_TIP_SHRINK;
        }
    }
    #initMessageboxControls() {
        const msgBox = this.#getMessagebox();
        if (!msgBox) { return; }
        // 为收起/展开Messagebox注册事件监听
        const toggleMessagebox = this.#toggleMessagebox;
        msgBox.addEventListener('click', (e) => {
            if (e.target != document.getElementById(PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE)) {
                toggleMessagebox();
            }
        });
        // 初始化脚本控制按钮状态
        this.#updateTroggleScriptStateButtonState(this.#getScriptPausedState());
        // 为暂停/开始按钮注册事件监听
        document.getElementById(PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE)?.addEventListener('click', this.#toggleScriptState);

    }
    #updateTroggleScriptStateButtonState(newState) {
        const btn = document.getElementById(PageMessageShower.#ID_BUTTON_TROGGLE_SCRIPT_PAUSE_STATE);
        if (!btn) { return; }
        btn.textContent = newState ? PageMessageShower.#BTN_RESUME_TEXT : PageMessageShower.#BTN_PAUSE_TEXT;
        btn.style.background = newState ? 'var(--btn-danger-bg)' : 'var(--btn-primary-bg)';
    }

    //#region 脚本状态管理
    #isScriptPaused = false;// 初始状态（默认 false）
    #getScriptPausedState() {
        return this.#isScriptPaused;
    }
    #setScriptPausedState(state) {
        this.#isScriptPaused = state;
    }
    #toggleScriptState() {
        const newState = !PageMessageShower.getInstance().#getScriptPausedState();
        PageMessageShower.getInstance().#setScriptPausedState(newState);
        PageMessageShower.getInstance().#updateTroggleScriptStateButtonState(newState);
        InfoShower.log([ConsoleLogger.instance, PageMessageShower.getInstance()], `脚本已${newState ? '暂停' : '恢复运行'}`);
        // 广播状态到其他标签页
        PageMessageShower.getInstance().#scriptPauseStateMessageChannel.postMessage({ type: PageMessageShower.#ID_SCRIPT_PAUSE_STATE, value: newState });
    }
    #listenScriptPauseStateChange() {
        // 监听来自其他页面的消息
        this.#scriptPauseStateMessageChannel.onmessage = function (e) {
            if (e.data.type === PageMessageShower.#ID_SCRIPT_PAUSE_STATE) {
                const isPaused = e.data.value;
                PageMessageShower.getInstance().#setScriptPausedState(isPaused);
                PageMessageShower.getInstance().#updateTroggleScriptStateButtonState(isPaused);
                InfoShower.log([ConsoleLogger.instance, PageMessageShower.getInstance()], `脚本状态已同步：${isPaused ? '暂停' : '运行'}`);
            }
        };
    }
    pauseScript() {
        if (!this.#getScriptPausedState()) {
            this.#toggleScriptState();
        }
    }
    resumeScript() {
        if (this.#getScriptPausedState()) {
            this.#toggleScriptState();
        }
    }
    async waitScriptResume() {
        await WaitUtil.waitUntil(() => !this.#getScriptPausedState(), 1 * 1000);
    }
    //#endregion  脚本状态管理

    //#endregion Messagebox创建及行为设定

    #output(msgLevel, msg) {
        let messagebox = this.#getMessagebox();
        if (!messagebox) {
            return;
        }
        let msgList = document.getElementById(PageMessageShower.#ID_MESSAGEBOX_CONTENT);
        if (msgList.children.length > PageMessageShower.#MAX_MESSAGE_COUNT - 1) {
            msgList.removeChild(msgList.children[0]);
        }
        let msgItem = document.createElement('div');
        msgItem.style.color = msgLevel == 'log' ? '#4e4eef' : (msgLevel == 'warn' ? '#f88f00' : '#ff0000');
        msgItem.innerText = msg;
        msgList.appendChild(msgItem);
    }
    log(msg) {
        this.#output('log', msg);
    }
    warn(msg) {
        this.#output('warn', msg);
    }
    error(msg) {
        this.#output('error', msg);
    }
}
//#endregion 信息展示工具

// 导出相关类
module.exports = {
    InfoShower,
    ConsoleLogger,
    PageMessageShower
};